// ==UserScript==
// @name         预警插件
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @author       You
// @match        http://10.4.192.46:8080/PIIAP/DataGather/StabilityClues/StabSupervision/list.jsp
// @grant        none
// @require      https://code.jquery.com/jquery-3.6.0.min.js
// ==/UserScript==

(function() {
    'use strict';
    
    // 等待页面和jQuery完全加载
    function waitForJQuery(callback) {
        if (typeof jQuery !== 'undefined') {
            callback();
        } else {
            setTimeout(function() {
                waitForJQuery(callback);
            }, 100);
        }
    }
    
    // 等待DataTables加载完成
    function waitForDataTable(callback) {
        const table = document.getElementById("DataTables_Table_0");
        if (table && table.rows && table.rows.length > 1) {
            callback();
        } else {
            setTimeout(function() {
                waitForDataTable(callback);
            }, 500);
        }
    }
    
    // 添加导出Excel功能
    function exportUnsignedExcel() {
        try {
            // 获取表格数据
            var table = document.getElementById("DataTables_Table_0");
            if (!table) {
                console.log("表格未找到");
                return;
            }
            
            // 创建CSV内容
            var csvContent = "序号,人员类型,姓名,证件号,下发次数,乘车时间,到达时间,上车站,车次,下车站,处理单位,签收用时(分),处理状态,处理结果,线索来源,操作\n";
            
            // 遍历表格行，只导出未签收的行
            for (var i = 1; i < table.rows.length; i++) {
                var row = table.rows[i];
                var processingStatus = row.cells[12] ? row.cells[12].innerText : ""; // 处理状态列
                var signTime = row.cells[11] ? row.cells[11].innerText : ""; // 签收用时列
                
                // 只导出未签收的信息：处理状态为空 或 签收用时为空
                if (processingStatus === "" || signTime === "") {
                    var rowData = [];
                    for (var j = 0; j < row.cells.length; j++) {
                        var cellText = row.cells[j].innerText.replace(/"/g, '""'); // 处理引号
                        rowData.push('"' + cellText + '"');
                    }
                    csvContent += rowData.join(",") + "\n";
                }
            }
            
            // 创建下载链接
            var blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
            var link = document.createElement("a");
            var url = URL.createObjectURL(blob);
            link.setAttribute("href", url);
            link.setAttribute("download", "未签收单位信息_" + new Date().toISOString().slice(0, 19).replace(/:/g, "-") + ".csv");
            link.style.visibility = 'hidden';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            
            console.log("已导出未签收单位Excel表：" + new Date());
        } catch (error) {
            console.error("导出Excel失败：", error);
        }
    }
    
    // 初始化插件
    function initPlugin() {
        // 使用原生JavaScript添加按钮
        var topStabElement = document.querySelector(".topStab");
        if (topStabElement) {
            topStabElement.innerHTML += "<button class='btn btn-warning radius' id='playBtn'>有未签收信息响铃后，点击控件静音.通知签收完毕后关闭静音！</button><button class='btn btn-success radius' id='exportBtn' style='margin-left: 10px;'>导出未签收单位Excel</button><audio id='voice' src='/PIIAP/DataGather/StabilityClues/tx.mp3' autostart='True' loop='-1' controls='controls' style='height: 0'></audio>";
            
            // 绑定按钮事件
            document.getElementById("playBtn").addEventListener("click", function(){
                var music = document.getElementById("voice");
                if (music.paused) {
                    music.play();
                } else {
                    music.pause();
                }
            });
            
            document.getElementById("exportBtn").addEventListener("click", function(){
                exportUnsignedExcel();
            });
            
            console.log("add playButton and exportButton：" + new Date());
        }
    }
    
    // 监控函数
    function startMonitoring() {
        setInterval(function(){
            console.log("Start Search：" + new Date());
            
            // 检查是否存在setTodayXf和search函数，如果不存在则跳过
            if (typeof window.setTodayXf === 'function') {
                window.setTodayXf();
            }
            if (typeof window.search === 'function') {
                window.search();
            }
            
            setTimeout(function(){
                var table = document.getElementById("DataTables_Table_0");
                if (table && table.rows && table.rows.length > 1) {
                    // 检查是否有未签收信息
                    var firstDataRow = table.rows[1];
                    if (firstDataRow && firstDataRow.cells && firstDataRow.cells[10]) {
                        if (firstDataRow.cells[10].innerText === "") {
                            var music = document.getElementById("voice");
                            if (music) {
                                music.play();
                            }
                            console.log("Start Warn：" + new Date());
                            
                            // 立即导出未签收单位Excel表
                            exportUnsignedExcel();
                        }
                    }
                }
            }, 1000);
        }, 1000 * 60 * (Math.round(Math.random() * 1 + 1)));
    }
    
    // 等待页面加载完成后初始化
    waitForJQuery(function() {
        // 等待DataTables加载
        waitForDataTable(function() {
            initPlugin();
            startMonitoring();
        });
    });
    
})(); 